package com.fh.shop.api.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.api.product.mapper.IProductMapper;
import com.fh.shop.api.product.po.Product;
import com.fh.shop.api.util.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class StockJob {
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private MailUtil mailUtil;
    @Value("${job.stock.limit}")
    private int stockLimit;
    @Value("${job.stock.mail}")
    private String mail;
    @Value("${job.stock.mail.title}")
    private String mailTitle;
    @Value("${job.stock.mail.files}")
    private List<String> filePathList;

    @Scheduled(cron = "0/30 * * * * ?")
    public void checkStock() {
        log.debug("检查库存=====");
        // 将库存量小于10的商品
        List<Product> productList = productMapper.findProductList(stockLimit);
        // 内容
        StringBuilder content = buildMailContent(productList);
        // 发给指定的人
//        mailUtil.sendMail(mail, mailTitle, content.toString());
        mailUtil.sendMailWithFile(mail, mailTitle, content.toString(), filePathList);
        log.debug("发送邮件成功=====");
    }

    private StringBuilder buildMailContent(List<Product> productList) {
        StringBuilder content = new StringBuilder();
        content.append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"1px\" width=\"500px\" bgcolor=\"#5f9ea0\">\n" +
                "<thead>\n" +
                "    <tr>\n" +
                "        <th>商品名</th>\n" +
                "        <th>价格</th>\n" +
                "        <th>品牌名</th>\n" +
                "        <th>分类名</th>\n" +
                "        <th>库存</th>\n" +
                "    </tr>\n" +
                "</thead>\n" +
                "<tbody>\n"
               );

        for (Product product : productList) {
            content.append("<tr>\n" +
                    "        <td>"+product.getProductName()+"</td>\n" +
                    "        <td>"+product.getPrice().toString()+"</td>\n" +
                    "        <td>"+product.getBrandName()+"</td>\n" +
                    "        <td>"+product.getCateName()+"</td>\n" +
                    "        <td>"+product.getStock()+"</td>\n" +
                    "    </tr>");
        }

        content.append("</tbody>\n" +
                "</table>");
        return content;
    }
}
